import { NextRequest, NextResponse } from 'next/server';
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();
const SCORE_MAP = {
  'HT1': 60, 'LT1': 45, 'HT2': 30, 'LT2': 20,
  'HT3': 10, 'LT3': 6, 'HT4': 4, 'LT4': 3,
  'HT5': 2, 'LT5': 1
};

// 获取单个玩家
export async function GET(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const playerId = parseInt(params.id);
    if (isNaN(playerId)) {
      return NextResponse.json(
        { error: '无效的玩家ID' },
        { status: 400 }
      );
    }

    const player = await prisma.player.findUnique({
      where: { id: playerId },
      include: { scores: true }
    });

    if (!player) {
      return NextResponse.json(
        { error: '玩家不存在' },
        { status: 404 }
      );
    }

    // 解析地区信息
    let player_region = player.region;
    let player_region_id = null;
    let player_region_color = null;
    let player_is_blacklisted = false;
    
    // 检查是否为黑名单
    if (player_region && player_region.includes('[blacklisted]')) {
      player_is_blacklisted = true;
      player_region = player_region.replace('[blacklisted]', '');
    }
    
    // 解析地区ID和颜色
    if (player_region && player_region.includes('|')) {
      const parts = player_region.split('|');
      player_region = parts[0];
      player_region_id = parts[1];
      player_region_color = parts[2];
    }

    const formattedPlayer = {
      ...player,
      id: player.id.toString(),
      region: player_region,
      region_id: player_region_id,
      region_color: player_region_color,
      is_blacklisted: player_is_blacklisted,
      scores: player.scores.map(score => ({
        ...score,
        id: score.id.toString(),
        playerId: score.playerId.toString(),
        value: SCORE_MAP[score.mode as keyof typeof SCORE_MAP] || 0
      }))
    };

    return NextResponse.json(formattedPlayer);
  } catch (error) {
    console.error('获取玩家失败:', error);
    return NextResponse.json(
      { error: '获取玩家失败' },
      { status: 500 }
    );
  }
}

// 更新玩家
export async function PUT(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const playerId = parseInt(params.id);
    if (isNaN(playerId)) {
      return NextResponse.json(
        { error: '无效的玩家ID' },
        { status: 400 }
      );
    }

    const { 
      name, 
      region, 
      avatar, 
      region_id, 
      region_color, 
      is_blacklisted,
      swordTier,
      crystalTier,
      buhcTier,
      potionTier,
      npotTier,
      smpTier
    } = await request.json();

    // 检查玩家是否存在
    const existingPlayer = await prisma.player.findUnique({
      where: { id: playerId }
    });

    if (!existingPlayer) {
      return NextResponse.json(
        { error: '玩家不存在' },
        { status: 404 }
      );
    }

    // 如果名称已更改，检查是否与其他玩家冲突
    if (name && name !== existingPlayer.name) {
      const nameConflict = await prisma.player.findUnique({
        where: { name }
      });
      
      if (nameConflict) {
        return NextResponse.json(
          { error: '该玩家名称已被使用' },
          { status: 400 }
        );
      }
    }

    // 处理地区信息
    let regionInfo = region;
    if (region && region_id && region_color) {
      regionInfo = `${region}|${region_id}|${region_color}`;
    }
    
    // 处理黑名单信息
    if (is_blacklisted !== undefined && regionInfo) {
      if (is_blacklisted) {
        // 仅当不存在[blacklisted]标记时才添加
        if (!regionInfo.includes('[blacklisted]')) {
          regionInfo = `${regionInfo}[blacklisted]`;
        }
      } else {
        // 移除[blacklisted]标记
        regionInfo = regionInfo.replace('[blacklisted]', '');
      }
    }
    
    // 更新玩家信息
    const updateData: any = {};
    
    if (name !== undefined) updateData.name = name;
    if (regionInfo !== undefined) updateData.region = regionInfo;
    if (avatar !== undefined) updateData.avatar = avatar;
    if (swordTier !== undefined) updateData.swordTier = swordTier;
    if (crystalTier !== undefined) updateData.crystalTier = crystalTier;
    if (buhcTier !== undefined) updateData.buhcTier = buhcTier;
    if (potionTier !== undefined) updateData.potionTier = potionTier;
    if (npotTier !== undefined) updateData.npotTier = npotTier;
    if (smpTier !== undefined) updateData.smpTier = smpTier;
    
    const updatedPlayer = await prisma.player.update({
      where: { id: playerId },
      data: updateData,
      include: { scores: true }
    });

    // 解析地区信息
    let player_region = updatedPlayer.region;
    let player_region_id = null;
    let player_region_color = null;
    let player_is_blacklisted = false;
    
    // 检查是否为黑名单
    if (player_region && player_region.includes('[blacklisted]')) {
      player_is_blacklisted = true;
      player_region = player_region.replace('[blacklisted]', '');
    }
    
    // 解析地区ID和颜色
    if (player_region && player_region.includes('|')) {
      const parts = player_region.split('|');
      player_region = parts[0];
      player_region_id = parts[1];
      player_region_color = parts[2];
    }

    const formattedPlayer = {
      ...updatedPlayer,
      id: updatedPlayer.id.toString(),
      region: player_region,
      region_id: player_region_id,
      region_color: player_region_color,
      is_blacklisted: player_is_blacklisted,
      scores: updatedPlayer.scores.map(score => ({
        ...score,
        id: score.id.toString(),
        playerId: score.playerId.toString()
      }))
    };

    return NextResponse.json({
      success: true,
      player: formattedPlayer
    });
  } catch (error) {
    console.error('更新玩家失败:', error);
    return NextResponse.json(
      { error: '更新玩家失败' },
      { status: 500 }
    );
  }
}

// 删除玩家
export async function DELETE(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const playerId = parseInt(params.id);
    if (isNaN(playerId)) {
      return NextResponse.json(
        { error: '无效的玩家ID' },
        { status: 400 }
      );
    }

    // 检查玩家是否存在
    const existingPlayer = await prisma.player.findUnique({
      where: { id: playerId }
    });

    if (!existingPlayer) {
      return NextResponse.json(
        { error: '玩家不存在' },
        { status: 404 }
      );
    }

    // 删除玩家
    await prisma.player.delete({
      where: { id: playerId }
    });

    return NextResponse.json({
      success: true,
      message: '玩家已成功删除'
    });
  } catch (error) {
    console.error('删除玩家失败:', error);
    return NextResponse.json(
      { error: '删除玩家失败' },
      { status: 500 }
    );
  }
}

// 处理更新数据的辅助函数
function updateData(
  name?: string, 
  region?: string, 
  avatar?: string,
  region_id?: string,
  region_color?: string,
  is_blacklisted?: boolean,
  swordTier?: number,
  crystalTier?: number,
  buhcTier?: number,
  potionTier?: number,
  npotTier?: number,
  smpTier?: number
) {
  const data: any = {};
  
  // 处理地区信息
  let regionInfo = region;
  if (region && region_id && region_color) {
    regionInfo = `${region}|${region_id}|${region_color}`;
  }
  
  // 处理黑名单信息
  if (is_blacklisted !== undefined && regionInfo) {
    if (is_blacklisted) {
      if (!regionInfo.includes('[blacklisted]')) {
        regionInfo = `${regionInfo}[blacklisted]`;
      }
    } else {
      regionInfo = regionInfo.replace('[blacklisted]', '');
    }
  }
  
  if (name !== undefined) data.name = name;
  if (regionInfo !== undefined) data.region = regionInfo;
  if (avatar !== undefined) data.avatar = avatar;
  if (swordTier !== undefined) data.swordTier = swordTier;
  if (crystalTier !== undefined) data.crystalTier = crystalTier;
  if (buhcTier !== undefined) data.buhcTier = buhcTier;
  if (potionTier !== undefined) data.potionTier = potionTier;
  if (npotTier !== undefined) data.npotTier = npotTier;
  if (smpTier !== undefined) data.smpTier = smpTier;
  
  return data;
} 